<template>
  <div class="avue-top">
    <div class="top-bar__right">
      <el-tooltip v-if="showDebug"
                  effect="dark"
                  :content="logsFlag?'没有错误日志':`${logsLen}条错误日志`"
                  placement="bottom">
        <div class="top-bar__item">
          <top-logs></top-logs>
        </div>
      </el-tooltip>

      <!--<i class="iconuser"></i>-->

      <div style="display: flex;justify-content: space-between;">
        <div>
          <div style="padding-bottom: 9px" @click.stop="goTo('/unreadMsg/index/false')">
            <span style="cursor:pointer">
               <img :src="`${publicPath}img/news.png`"
                    style="width:15px;position: relative;
                                  left: 0;
                                  top: 2px;">
              <el-badge :value="unreadMsgTotal" class="el-badge-news" v-if="unreadMsgTotal != 0">
                <span style="color: white;font-size: 15px;margin-left: 5px;">消息</span>
              </el-badge>
                <span style="color: white;font-size: 15px;margin-left: 5px;" v-if="unreadMsgTotal == 0">消息</span>
            </span>
          </div>
        </div>

        <div>
          <el-dropdown v-if="userInfo.username">
            <span class="el-dropdown-link" style="margin-left: 24px">
              <img :src="`${publicPath}img/user-white.png`"
                   style="width:15px;position: relative;
                        left: 0;
                        top: 2px;">
              <span style="color: white;font-size: 15px;cursor:pointer">
                {{userInfo.nickname}}
                <i style="margin-left:4px;line-height:34px;"
                   class="el-icon-arrow-down"></i>
              </span>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-card class="box-card">
                <div>
                  <div style="overflow: hidden">
                    <span>用户名 :</span><span class="top_dropdown_span">{{userDetail.username}}</span>
                  </div>
                  <div class="top-divider">
                    <el-divider></el-divider>
                  </div>

                  <div style="overflow: hidden">
                    <span>用户全称 :</span><span class="top_dropdown_span">{{userDetail.fullname}}</span>
                  </div>
                  <div class="top-divider">
                    <el-divider></el-divider>
                  </div>

                  <div style="overflow: hidden">
                    <span>所属部门 :</span><span class="top_dropdown_span">{{userDetail.deptName}}</span>
                  </div>
                  <div class="top-divider">
                    <el-divider></el-divider>
                  </div>

                  <div style="overflow: hidden">
                    <span>所在地区 :</span><span class="top_dropdown_span">{{userDetail.areaName}}</span>
                  </div>
                  <div class="top-divider">
                    <el-divider></el-divider>
                  </div>

                  <div style="overflow: hidden">
                    <span>平台角色 :</span><span class="top_dropdown_span">{{dealRoles(userDetail.roleCodes)}}</span>
                  </div>
                  <div class="top-divider">
                    <el-divider></el-divider>
                  </div>
                </div>
                <div style="display: flex;justify-content: space-between">
                  <span @click="updatePassword()" style="cursor:pointer;" class="el-icon-setting">修改密码</span>
                  <span style="cursor:pointer;" v-if="userHasAdminRole(userDetail.roleCodes)" class="el-icon-setting"><a :href="consoleIndex">后台管理</a></span>
                  <span @click="logout()" style="cursor:pointer;" class="el-icon-warning">退出系统</span>
                </div>
              </el-card>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <span style="color: #fff;font-size: 18px;margin-left: 9px;"
            @click.stop="loginTo()"
            v-if="!userInfo.username">
        <p style="font-size: 16px;display:inline-block;">注册/登录</p>
      </span>
    </div>
    <el-dialog title="修改密码"
               :visible.sync="addTargetVisible"
               width="700px">
      <el-form label-width="130px"
               :model="userUpdateDTO"
               style="padding-right: 30px;"
               :rules="updatePasswordRules"
               ref="userUpdateDTO">
        <el-row>
          <el-col :span="18">
            <el-form-item class="form-item is-required"
                          label="原始密码 :"
                          prop="oldPassword">
              <el-input v-model="userUpdateDTO.oldPassword"
                        type="password"
                        placeholder="请输入原始密码"
                        auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item class="form-item is-required"
                          label="新密码 :"
                          prop="newPassword">
              <el-input v-model="userUpdateDTO.newPassword"
                        type="password"
                        placeholder="请输入新密码"
                        auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item class="form-item is-required"
                          label="新密码 :"
                          prop="reNewPassword">
              <el-input type="password"
                        v-model="userUpdateDTO.reNewPassword"
                        placeholder="请确定密码"
                        auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer"
           class="dialog-footer"
           style="margin-top: -50px;">
        <el-button @click="cancelTargetWindow()">关闭</el-button>
        <el-button type="primary"
                   @click="resetPassword()">修改
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {mapGetters, mapState} from "vuex";
  import {fullscreenToggel, listenfullscreen, handleImg} from "@/util/util";
  import logo from "../logo";
  import topLock from "./top-lock";
  import topMenu from "./top-menu";
  import topSearch from "./top-search";
  import topTheme from "./top-theme";
  import topLogs from "./top-logs";
  import topColor from "./top-color";
  import topSetting from "./top-setting";
  import {updatePasswordSave} from "@/api/admin/user";
  import {getCurrentUserDetail,getunreadMsg} from "@/api/system";

  export default {
    components: {
      topLock,
      topMenu,
      topSearch,
      topTheme,
      topLogs,
      topColor,
      topSetting
    },
    name: "top",
    data() {
      var validatePass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入新密码'));
        } else if (value.toString().length < 6 || value.toString().length > 18) {
          callback(new Error('密码长度为6 - 18个字符'))
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.userUpdateDTO.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        consoleIndex: process.env.VUE_APP_CONSOLE_INDEX,
        publicPath: process.env.BASE_URL,
        showDebug: false,
        showTheme: true,
        showLock: false,
        showFullScren: true,
        showCollapse: false,
        showSearch: false,
        showMenu: false,
        showColor: true,
        addTargetVisible: false,
        userUpdateDTO: {},
        updatePasswordRules: {
          oldPassword: [{required: true, message: "请输入原始密码"}],
          newPassword: [
            {required: true, validator: validatePass, trigger: 'blur'}
          ],
          reNewPassword: [
            {required: true, validator: validatePass2, trigger: 'blur'}
          ]
        },
        userDetail: {
          username: null,
          nickname: null,
          fullname: null,
          deptName: null,
          roleCodes: [],
          areaName: null,
        },
        unreadMsgTotal: 0,//通知消息数量

      };
    },
    filters: {},
    created() {
      getCurrentUserDetail().then(response => {
        if (response.data.code == 0) {
          this.userDetail.username = response.data.data.sysUser.username;
          this.userDetail.nickname = response.data.data.sysUser.nickname;
          this.userDetail.fullname = response.data.data.sysDept.fullname;
          this.userDetail.deptName = response.data.data.deptName;
          this.userDetail.roleCodes = response.data.data.roleCodes;
          this.userDetail.areaName = response.data.data.areaName;
        }
      })
      this.getUnreadTotal();
    },
    mounted() {
      listenfullscreen(this.setScreen);
    },
    computed: {
      ...mapGetters([
        "userInfo",
        "isFullScren",
        "tagWel",
        "tagList",
        "isCollapse",
        "tag",
        "logsLen",
        "logsFlag"
      ])
    },
    methods: {
      userHasAdminRole(roleCodes){
        let userHasAdminRole = false;
        if(roleCodes != null && Array.isArray(roleCodes) && roleCodes.length > 0){
          for(let roleCode of roleCodes){
            if(roleCode.match(/ROLE.*_ADMIN/i)){
              userHasAdminRole = true;
              break;
            }
          }
        }
        return userHasAdminRole;
      },
      handleScreen() {
        fullscreenToggel();
      },
      setCollapse() {
        this.$store.commit("SET_COLLAPSE");
      },
      setScreen() {
        this.$store.commit("SET_FULLSCREN");
      },
      loginTo() {
        this.$router.push({path: "/login"});
      },
      logout() {
        this.$confirm("是否退出系统, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$store.dispatch("LogOut").then(() => {
            this.$router.push({path: "/login"});
          });
        });
      },
      updatePassword() {
        this.addTargetVisible = true
      },
      cancelTargetWindow() {
        this.addTargetVisible = false;
      },
      resetPassword() {
        this.$refs.userUpdateDTO.validate(valid => {
          if (valid) {
            updatePasswordSave(this.userUpdateDTO).then(response => {
              if (response.data.data) {
                this.$notify({
                  title: "成功",
                  message: "修改成功,请重新登录",
                  type: "success",
                  duration: 2000
                });
                this.addTargetVisible = false;
                this.$store.dispatch("LogOut").then(() => {
                  this.$router.push({path: "/login"});
                });
              } else {
                this.$notify({
                  title: "失败",
                  message: response.data.msg,
                  type: "fail",
                  duration: 2000
                });
              }
            })
          }
        })
      },
      dealRoles(roleCodes) {
        let roleCodesString = '';
        if (roleCodes.length != 0) {
          for (let item in roleCodes) {
            switch (roleCodes[item]) {
              case 'ROLE_ADMIN':
                roleCodesString = roleCodesString + '管理员' + ',';
                break;
              case 'ROLE_PT':
                roleCodesString = roleCodesString + '部门用户' + ',';
                break;
              case 'ROLE_ZYZY_PT':
                roleCodesString = roleCodesString + '自然资源厅普通角色' + ',';
                break;
              case 'ROLE_FGW_PT':
                roleCodesString = roleCodesString + '发改委普通角色' + ',';
                break;
              case 'ROLE_FGT_GL':
                roleCodesString = roleCodesString + '发改委管理角色' + ',';
                break;
              case 'ROLE_ZRZY_GL':
                roleCodesString = roleCodesString + '自然资源管理角色' + ',';
                break;
              case 'ROLE_ZF_GL':
                roleCodesString = roleCodesString + '政府部门管理角色' + ',';
                break;
              case 'ROLE_RD_GL':
                roleCodesString = roleCodesString + '人大管理角色' + ',';
                break;
              case 'ROLE_DW_GL':
                roleCodesString = roleCodesString + '党委角色' + ',';
                break;

            }
          }
        }
        return roleCodesString;
      },
      goTo(path, query) {
        this.$router.push({
          path: path,
          query: query
        });
      },
      getUnreadTotal() {
        getunreadMsg(Object.assign({
          current: 1,
          size: 1,
          haveRead: false,
        })).then(response => {
          if (response.data.code == '0') {
            this.unreadMsgTotal = response.data.data.total;
          }
        })
      },


    }
  };
</script>

<style lang="scss" scoped>
  .avue-top {
    color: rgba(0, 0, 0, 0.65);
    font-size: 28px;
    height: 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    white-space: nowrap;
  }

  .top-bar__right {
    height: 34px;
    float: right;
    right: -1px;
    top: 30px;

    .el-dropdown {
      height: 34px;
      line-height: 34px;
    }
  }

  .top-label {
    color: #fff;
    font-size: 16px;
    display: inline-block;
    line-height: 35px;
    margin-left: 6px;
    margin-right: 12px;
  }

  .box-card {
    width: 320px;
  }

  .clearfix:after {
    clear: both
  }

  .top-divider {
    /deep/ .el-divider--horizontal {
      margin: 12px 0px;
    }
  }

  .top_dropdown_span {
    float: right;
    width: 180px;
    display: block;
    color: #309bde;
  }

  .el-badge-news {
    margin-bottom: 6px;
  }
</style>
